var express = require('express');
var path = require('path');
const fs = require('fs')
//const https = require('https')
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var FileStreamRotator = require('file-stream-rotator');
var createError = require('http-errors');
require('body-parser-xml')(bodyParser);
const moment = require('moment');
const Remind = require('./utils/remind'); // 定时任务模块

var bossRouter = require('./routes/boss'); // crm后台管理路由

var app = express();

//设置允许跨域访问该服务.
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Credentials', 'true')
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', '*');
  res.header("Access-Control-Allow-Headers", "*");
  //res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});

// 解决微信回调数据请求体为xml时（没有这一段代码，req.body为:{}）
app.use(bodyParser.xml({
  limit: '2MB',   // Reject payload bigger than 1 MB
  xmlParseOptions: {
    normalize: true,     // Trim whitespace inside text nodes
    normalizeTags: true, // Transform tags to lowercase
    explicitArray: false // Only put nodes in array if >1
  }
}))

// -----日志处理 start-------
var logDirectory = path.join(__dirname, 'logs');
//确保存储的路径存在 
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
// 创建输出流
var errorLogStream = FileStreamRotator.getStream({
 date_format: 'YYYYMMDD', //日期类型
 filename: path.join(logDirectory, '%DATE%-error.log'), //文件名
 frequency: 'daily', //每天的频率
 verbose: false
});
// 创建输出流
var accessLogStream = FileStreamRotator.getStream({
    date_format: 'YYYYMMDD',
    filename: path.join(logDirectory, '%DATE%-access.log'),
    frequency: 'daily',
    verbose: false
});
// 写正常访问请求的log日志
// ---自定义日志输出格式 start ：目的是让日志日期于本地一致
logger.token('localDate',function getDate(req){
  //let date = new Date();
  //return date.toLocaleString()
  return moment().format('YYYY-MM-DD HH:mm:ss')
})
logger.format('myCombined',':remote-addr - :remote-user [:localDate] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"')
// ---自定义日志输出格式 end

app.use(logger('myCombined', {
  immediate:true, // 在请求到达时打印日志，而不是请求响应完成时。这意味着即使服务器崩溃，日志也会打印，但是响应的数据无法被打印
  stream: accessLogStream
}));
//写访问出错的log日志
app.use(logger('myCombined', {
    immediate:true,  
    skip: function (req, res) {
      return res.statusCode < 400
    },
    stream: errorLogStream
}));
// -----日志处理 end-------

// view engine setup
app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'ejs');  // 直接渲染ejs模板文件

app.engine('.html', require('ejs').__express) //define tempalte engine
app.set('view engine', 'html') // 渲染html模板文件

app.use(logger('dev'));
app.use(express.json({limit: '50mb'}));  // limit: '50mb' 解决无法接受大数据传输问题，如前端传base64
app.use(express.urlencoded({ limit: '50mb',extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/boss', bossRouter);

// 启动每周问题汇总定时任务
Remind.weeklyReminder()


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
